

<!DOCTYPE html>
<html lang="zh-CN" data-default-color-scheme=auto>



<head>
  <meta charset="UTF-8">
  <link rel="apple-touch-icon" sizes="76x76" href="/img/favicon.png">
  <link rel="icon" href="/img/favicon.png">
  <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=5.0, shrink-to-fit=no">
  <meta http-equiv="x-ua-compatible" content="ie=edge">
  
  <meta name="theme-color" content="#2f4154">
  <meta name="description" content="">
  <meta name="author" content="John Doe">
  <meta name="keywords" content="">
  <meta name="description" content="前端文件分片上传流程介绍作为一个前端，平常工作中肯定离不开文件上传的业务需求，可能大部分情况都是对图片，附件等一些小文件进行上传，但是当需要上传大文件的时候，使用普通上传方式时，可能就会看到接口返回413，这里就需要提到本文所要说的文件分片上传。     正文二进制数据类型前端对二进制数据的存储格式有很多种。    input输入框上传文件时用到的File类型。  视频网站上能看到的blob链接资">
<meta property="og:type" content="article">
<meta property="og:title" content="文件分片上传">
<meta property="og:url" content="http://yoursite.com/2021/11/24/%E6%96%87%E4%BB%B6%E5%88%86%E7%89%87%E4%B8%8A%E4%BC%A0/index.html">
<meta property="og:site_name" content="Food-Billboard">
<meta property="og:description" content="前端文件分片上传流程介绍作为一个前端，平常工作中肯定离不开文件上传的业务需求，可能大部分情况都是对图片，附件等一些小文件进行上传，但是当需要上传大文件的时候，使用普通上传方式时，可能就会看到接口返回413，这里就需要提到本文所要说的文件分片上传。     正文二进制数据类型前端对二进制数据的存储格式有很多种。    input输入框上传文件时用到的File类型。  视频网站上能看到的blob链接资">
<meta property="og:locale" content="zh_CN">
<meta property="article:published_time" content="2021-11-24T05:56:00.000Z">
<meta property="article:modified_time" content="2021-11-24T08:48:05.000Z">
<meta property="article:author" content="John Doe">
<meta property="article:tag" content="upload file chunk">
<meta name="twitter:card" content="summary_large_image">
  
  <title>文件分片上传 - Food-Billboard</title>

  <link  rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4/dist/css/bootstrap.min.css" />


  <link  rel="stylesheet" href="https://cdn.jsdelivr.net/npm/github-markdown-css@4/github-markdown.min.css" />
  <link  rel="stylesheet" href="/lib/hint/hint.min.css" />

  
    
    
      
      <link  rel="stylesheet" href="https://cdn.jsdelivr.net/npm/highlight.js@10/styles/github-gist.min.css" />
    
  

  
    <link  rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fancyapps/fancybox@3/dist/jquery.fancybox.min.css" />
  


<!-- 主题依赖的图标库，不要自行修改 -->

<link rel="stylesheet" href="//at.alicdn.com/t/font_1749284_ba1fz6golrf.css">



<link rel="stylesheet" href="//at.alicdn.com/t/font_1736178_kmeydafke9r.css">


<link  rel="stylesheet" href="/css/main.css" />

<!-- 自定义样式保持在最底部 -->


  <script id="fluid-configs">
    var Fluid = window.Fluid || {};
    var CONFIG = {"hostname":"yoursite.com","root":"/","version":"1.8.12","typing":{"enable":true,"typeSpeed":70,"cursorChar":"_","loop":false},"anchorjs":{"enable":true,"element":"h1,h2,h3,h4,h5,h6","placement":"right","visible":"hover","icon":""},"progressbar":{"enable":true,"height_px":3,"color":"#29d","options":{"showSpinner":false,"trickleSpeed":100}},"copy_btn":true,"image_zoom":{"enable":true,"img_url_replace":["",""]},"toc":{"enable":true,"headingSelector":"h1,h2,h3,h4,h5,h6","collapseDepth":0},"lazyload":{"enable":true,"loading_img":"/img/loading.gif","onlypost":false,"offset_factor":2},"web_analytics":{"enable":false,"baidu":null,"google":null,"gtag":null,"tencent":{"sid":null,"cid":null},"woyaola":null,"cnzz":null,"leancloud":{"app_id":null,"app_key":null,"server_url":null,"path":"window.location.pathname"}},"search_path":"/local-search.xml"};
  </script>
  <script  src="/js/utils.js" ></script>
  <script  src="/js/color-schema.js" ></script>
<!-- hexo injector head_end start -->
  <link rel="stylesheet" href="//cdn.jsdelivr.net/gh/bynotes/texiao/source/css/toubudaziji.css"></link>
  <link rel="stylesheet" href="//cdn.jsdelivr.net/gh/bynotes/texiao/source/css/shubiao.css"></link>
<!-- hexo injector head_end end --><meta name="generator" content="Hexo 5.4.0"></head>


<body>
  <header style="height: 70vh;">
    <nav id="navbar" class="navbar fixed-top  navbar-expand-lg navbar-dark scrolling-navbar">
  <div class="container">
    <a class="navbar-brand" href="/">
      <strong>Fluid</strong>
    </a>

    <button id="navbar-toggler-btn" class="navbar-toggler" type="button" data-toggle="collapse"
            data-target="#navbarSupportedContent"
            aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
      <div class="animated-icon"><span></span><span></span><span></span></div>
    </button>

    <!-- Collapsible content -->
    <div class="collapse navbar-collapse" id="navbarSupportedContent">
      <ul class="navbar-nav ml-auto text-center">
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/">
                <i class="iconfont icon-home-fill"></i>
                首页
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/project">
                <i class="iconfont icon-books"></i>
                项目
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/archives/">
                <i class="iconfont icon-archive-fill"></i>
                归档
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/categories/">
                <i class="iconfont icon-category-fill"></i>
                分类
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/tags/">
                <i class="iconfont icon-tags-fill"></i>
                标签
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/about/">
                <i class="iconfont icon-user-fill"></i>
                关于
              </a>
            </li>
          
        
        
          <li class="nav-item" id="search-btn">
            <a class="nav-link" target="_self" href="javascript:;" data-toggle="modal" data-target="#modalSearch" aria-label="Search">
              &nbsp;<i class="iconfont icon-search"></i>&nbsp;
            </a>
          </li>
        
        
          <li class="nav-item" id="color-toggle-btn">
            <a class="nav-link" target="_self" href="javascript:;" aria-label="Color Toggle">&nbsp;<i
                class="iconfont icon-dark" id="color-toggle-icon"></i>&nbsp;</a>
          </li>
        
      </ul>
    </div>
  </div>
</nav>

    <div class="banner" id="banner" parallax=true
         style="background: url('/images/%E6%96%87%E4%BB%B6%E5%88%86%E7%89%87%E4%B8%8A%E4%BC%A0/background.jpg') no-repeat center center;
           background-size: cover;">
      <div class="full-bg-img">
        <div class="mask flex-center" style="background-color: rgba(0, 0, 0, 0.3)">
          <div class="page-header text-center fade-in-up">
            <span class="h2" id="subtitle" title="文件分片上传">
              
            </span>

            
              <div class="mt-3">
  
  
    <span class="post-meta">
      <i class="iconfont icon-date-fill" aria-hidden="true"></i>
      <time datetime="2021-11-24 13:56" pubdate>
        2021年11月24日 下午
      </time>
    </span>
  
</div>

<div class="mt-1">
  
    <span class="post-meta mr-2">
      <i class="iconfont icon-chart"></i>
      3.5k 字
    </span>
  

  
    <span class="post-meta mr-2">
      <i class="iconfont icon-clock-fill"></i>
      
      
      11 分钟
    </span>
  

  
  
</div>

            
          </div>

          
        </div>
      </div>
    </div>
  </header>

  <main>
    
      

<div class="container-fluid nopadding-x">
  <div class="row nomargin-x">
    <div class="d-none d-lg-block col-lg-2"></div>
    <div class="col-lg-8 nopadding-x-md">
      <div class="container nopadding-x-md" id="board-ctn">
        <div class="py-5" id="board">
          <article class="post-content mx-auto">
            <!-- SEO header -->
            <h1 style="display: none">文件分片上传</h1>
            
            <div class="markdown-body">
              <h2 id="前端文件分片上传流程"><a href="#前端文件分片上传流程" class="headerlink" title="前端文件分片上传流程"></a>前端文件分片上传流程</h2><h2 id="介绍"><a href="#介绍" class="headerlink" title="介绍"></a>介绍</h2><p>作为一个前端，平常工作中肯定离不开文件上传的业务需求，可能大部分情况都是对图片，附件等一些小文件进行上传，但是当需要上传大文件的时候，使用普通上传方式时，可能就会看到接口返回<code>413</code>，这里就需要提到本文所要说的文件分片上传。    </p>
<h2 id="正文"><a href="#正文" class="headerlink" title="正文"></a>正文</h2><h3 id="二进制数据类型"><a href="#二进制数据类型" class="headerlink" title="二进制数据类型"></a>二进制数据类型</h3><p>前端对二进制数据的存储格式有很多种。  </p>
<ul>
<li><code>input</code>输入框上传文件时用到的<a target="_blank" rel="noopener" href="https://developer.mozilla.org/zh-CN/docs/Web/API/File">File</a>类型。 </li>
<li>视频网站上能看到的<code>blob</code>链接资源  </li>
<li><code>es6</code>中出现的<code>ArrayBuffer</code>，并且是文件分片上传，断点续传的基础。   </li>
<li>还有一个就是<code>base64</code>  </li>
</ul>
<h3 id="不同类型的相互转换"><a href="#不同类型的相互转换" class="headerlink" title="不同类型的相互转换"></a>不同类型的相互转换</h3><p>很多数据类型的转换都需要依靠于<a target="_blank" rel="noopener" href="https://developer.mozilla.org/zh-CN/docs/Web/API/FileReader">FileReader</a>  </p>
<ol>
<li><code>ArrayBuffer to Blob</code>  </li>
</ol>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><code class="hljs js"><span class="hljs-keyword">const</span> blob = <span class="hljs-keyword">new</span> Blob([<span class="hljs-keyword">new</span> <span class="hljs-built_in">ArrayBuffer</span>(<span class="hljs-number">1024</span>)])  <br><span class="hljs-keyword">const</span> fileReader = <span class="hljs-keyword">new</span> FileReader()<br><br>fileReader.onload = <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params"></span>) </span>&#123;<br>  <span class="hljs-built_in">console</span>.log(fileReader.result)<br>&#125;<br><br>fileReader.readAsArrayBuffer(blob)<br><br></code></pre></td></tr></table></figure>

<ol start="2">
<li><code>Blob to Base64</code>  </li>
</ol>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><code class="hljs js"><span class="hljs-keyword">const</span> blob = <span class="hljs-keyword">new</span> Blob([<span class="hljs-keyword">new</span> <span class="hljs-built_in">ArrayBuffer</span>(<span class="hljs-number">1024</span>)])  <br><span class="hljs-keyword">const</span> fileReader = <span class="hljs-keyword">new</span> FileReader()<br><br>fileReader.onload = <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params"></span>) </span>&#123;<br>  <span class="hljs-built_in">console</span>.log(fileReader.result)<br>&#125;<br><br>fileReader.readAsDataURL(blob)<br></code></pre></td></tr></table></figure>

<p>以上是两个简单的数据类型转换的例子   </p>
<h3 id="需要使用到的npm-package"><a href="#需要使用到的npm-package" class="headerlink" title="需要使用到的npm package"></a>需要使用到的npm package</h3><ul>
<li><code>spark-md5</code><br><a target="_blank" rel="noopener" href="https://www.npmjs.com/package/spark-md5">spark-md5</a>可以将对应的数据进行<code>md5</code>加密，这样在下一次对同一个文件进行上传时，可以直接跳过整个上传流传，实现秒传的效果。  </li>
</ul>
<h3 id="具体流程"><a href="#具体流程" class="headerlink" title="具体流程"></a>具体流程</h3><ul>
<li><p><code>input</code>接收文件<code>template.mp4</code>  </p>
</li>
<li><p>获取文件的基础信息  </p>
<ul>
<li>文件的<code>mime</code>，当前的类型是<code>video/mp4</code>  </li>
<li>文件的大小<code>file.size</code>，假设本次文件的大小为<code>1G</code>  </li>
<li>设置本次上传分片的大小为<code>5M</code>  </li>
<li>计算本次上传的分片数量为<code>1G / 5M = 205</code>，所以本次需要上传205次  </li>
</ul>
</li>
<li><p>对文件进行分片  </p>
<ul>
<li>使用<code>spark-md5</code>进行分片  <figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br></pre></td><td class="code"><pre><code class="hljs js"><span class="hljs-keyword">import</span> &#123; <span class="hljs-built_in">ArrayBuffer</span> &#125; <span class="hljs-keyword">from</span> <span class="hljs-string">&#x27;spark-md5&#x27;</span><br><br><span class="hljs-keyword">const</span> SparkMd5 = <span class="hljs-keyword">new</span> <span class="hljs-built_in">ArrayBuffer</span>()<br><br><span class="hljs-comment">// 保存分片用于在后面上传时用  </span><br><span class="hljs-keyword">const</span> cacheChunks = []<br><span class="hljs-comment">// 当前分片的索引</span><br><span class="hljs-keyword">const</span> index = <span class="hljs-number">0</span><br><span class="hljs-comment">// 分片的大小</span><br><span class="hljs-keyword">const</span> chunkSize = <span class="hljs-number">1024</span> * <span class="hljs-number">1024</span> * <span class="hljs-number">5</span> <br><span class="hljs-comment">// file 只需要简单调用 file.slice 就可以</span><br><span class="hljs-keyword">const</span> currentChunk = file.slice(index * chunkSize, (index + <span class="hljs-number">1</span>) * chunkSize)  <br><br>cacheChunks.push(currentChunk)<br><br><span class="hljs-comment">// 添加分片  </span><br>SparkMd5.append(currentChunk)<br><br><span class="hljs-comment">// 所有分片添加完成时  </span><br><span class="hljs-keyword">const</span> md5 = SparkMd5.end()<br><br><span class="hljs-comment">// 完成解析后销毁对应实例  </span><br>SparkMd5.destroy()<br><br></code></pre></td></tr></table></figure>
</li>
</ul>
</li>
<li><p>文件存在性检查<br>将文件的一些信息传递给后台，服务端检查文件是否存在。<br>如果存在，则跳过之后的上传过程。<br>如果不存在，则继续后面的上传流程。  </p>
</li>
<li><p>文件分片上传<br>按照索引顺序对文件分片进行上传  </p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><code class="hljs js"><span class="hljs-keyword">import</span> axios <span class="hljs-keyword">from</span> <span class="hljs-string">&#x27;axios&#x27;</span><br><br><span class="hljs-keyword">const</span> formData = <span class="hljs-keyword">new</span> FormData()<br><span class="hljs-comment">// 需要上传的文件分片</span><br>formData.append(<span class="hljs-string">&quot;file&quot;</span>, chunk)<br><span class="hljs-comment">// 当前分片的索引  </span><br>formData.append(<span class="hljs-string">&quot;index&quot;</span>, index)<br><span class="hljs-comment">// 文件md5 </span><br>formData.append(<span class="hljs-string">&quot;md5&quot;</span>, md5)<br><br>axios.post(<span class="hljs-string">&quot;/path/to/upload&quot;</span>, formData)<br><br></code></pre></td></tr></table></figure>
<p>后端通过返回下一分片的索引或者是下一分片的范围来指定前端接下来需要上传的分片<br>在上一步骤中也可以返回和这一步骤相同的内容。  </p>
</li>
<li><p>文件上传完成通知<br>这一步骤为可选步骤，通过前端通知后端完成了所有文件分片的上传。<br>一般不需要前端主动向后端通知。  </p>
</li>
</ul>
<h3 id="后端实现"><a href="#后端实现" class="headerlink" title="后端实现"></a>后端实现</h3><p>这里简单使用<code>node</code>讲解一下后端接收文件的基本逻辑<br>使用<code>koa</code>做基础服务<br>使用<code>koa-body</code>接收前端的文件内容<br>使用<code>koa-router</code>做对应的restful设计  </p>
<ol>
<li><p>文件存在性检查</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br></pre></td><td class="code"><pre><code class="hljs js"><br><span class="hljs-keyword">let</span> fileCache = &#123;&#125;<br><br>router<br>.get(<span class="hljs-string">&quot;/&quot;</span>, <span class="hljs-keyword">async</span> (ctx) =&gt; &#123;<br>  <span class="hljs-keyword">const</span> &#123; md5, chunkSize, filename, size, length &#125; = ctx.query <br>  <span class="hljs-keyword">if</span>(fileCache[md5] &amp;&amp; fileCache[md5].chunks.length === length) &#123;<br>    ctx.body = &#123;<br>      <span class="hljs-attr">success</span>: <span class="hljs-literal">true</span>,<br>      <span class="hljs-attr">res</span>: &#123;<br>        <span class="hljs-attr">data</span>: <span class="hljs-literal">true</span> <br>      &#125;<br>    &#125;<br>    <span class="hljs-keyword">return</span><br>  &#125;<span class="hljs-keyword">else</span> <span class="hljs-keyword">if</span>(fileCache[md5]) &#123;<br>    <span class="hljs-keyword">const</span> index = findLastUnUploadChunkIndex()<br>    ctx.body = &#123;<br>      <span class="hljs-attr">success</span>: <span class="hljs-literal">true</span>,<br>      <span class="hljs-attr">res</span>: &#123;<br>        <span class="hljs-attr">data</span>: index<br>      &#125;<br>    &#125;<br>  &#125;<span class="hljs-keyword">else</span> &#123;<br>    fileCache[md5] = &#123;<br>      <span class="hljs-attr">chunks</span>: [],<br>      size,<br>      length,<br>      chunkSize,<br>      md5<br>    &#125;<br>    ctx.body = &#123;<br>      <span class="hljs-attr">success</span>: <span class="hljs-literal">true</span>,<br>      <span class="hljs-attr">res</span>: &#123;<br>        <span class="hljs-attr">data</span>: <span class="hljs-number">0</span><br>      &#125;<br>    &#125;<br>  &#125;<br>&#125;)<br></code></pre></td></tr></table></figure>
</li>
<li><p>文件上传  </p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><code class="hljs js">router.post(<span class="hljs-string">&quot;/&quot;</span>, <span class="hljs-keyword">async</span> (ctx) =&gt; &#123;<br>  <span class="hljs-keyword">const</span> files = ctx.request.files.file <br>  <span class="hljs-keyword">const</span> &#123; md5, index &#125; = ctx.request.body <br>  fileCache[md5].chunks.push(index) <br>  <span class="hljs-comment">// 使用fs保存对应的分片至指定文件夹</span><br>  <span class="hljs-comment">// 分片名称可以使用md5-index的形式</span><br>&#125;)<br></code></pre></td></tr></table></figure>
</li>
<li><p>文件合并  </p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br></pre></td><td class="code"><pre><code class="hljs js"><span class="hljs-keyword">const</span> fs = <span class="hljs-built_in">require</span>(<span class="hljs-string">&quot;fs&quot;</span>)<br><span class="hljs-keyword">const</span> fsPromise = fs.promises  <br><br><span class="hljs-comment">// 合并分片</span><br><span class="hljs-keyword">async</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">mergeChunk</span>(<span class="hljs-params"></span>) </span>&#123;<br><br>  <span class="hljs-keyword">const</span> realFilePath = <span class="hljs-string">&quot;/path/to/real/file&quot;</span><br><br>  <span class="hljs-comment">// 获取对应的文件分片文件名称  </span><br>  <span class="hljs-keyword">const</span> chunkList = <span class="hljs-keyword">await</span> fsPromise.readdir(<span class="hljs-string">&quot;/path/to/chunk&quot;</span>)  <br><br>  <span class="hljs-comment">// 对文件进行排序  </span><br>  chunkList.sort(<span class="hljs-function">(<span class="hljs-params">suffixA, suffixB</span>) =&gt;</span> <span class="hljs-built_in">Number</span>(suffixA.split(<span class="hljs-string">&#x27;-&#x27;</span>)[<span class="hljs-number">1</span>]) - <span class="hljs-built_in">Number</span>(suffixB.split(<span class="hljs-string">&#x27;-&#x27;</span>)[<span class="hljs-number">1</span>]))<br>  <br>  <span class="hljs-comment">//文件合并</span><br>  <span class="hljs-keyword">const</span> mergeTasks = <span class="hljs-keyword">async</span> () =&gt; &#123;<br>    <span class="hljs-keyword">for</span>(<span class="hljs-keyword">let</span> i = <span class="hljs-number">0</span>; i &lt; chunkList.length; i ++) &#123;<br>      <span class="hljs-keyword">const</span> chunk = chunkList[i]<br>      <span class="hljs-keyword">await</span> fs.readFile(chunk)<br>      .then(<span class="hljs-function"><span class="hljs-params">data</span> =&gt;</span> fs.appendFile(realFilePath, data))<br>      .then(<span class="hljs-function"><span class="hljs-params">_</span> =&gt;</span> fs.unlink(chunk))<br>    &#125;<br>  &#125;<br><br>  <span class="hljs-keyword">return</span> fs.writeFile(realFilePath, <span class="hljs-string">&#x27;&#x27;</span>)<br>  .then(mergeTasks)<br>  .catch(<span class="hljs-function"><span class="hljs-params">err</span> =&gt;</span> &#123;&#125;)<br>&#125;<br><br></code></pre></td></tr></table></figure>

</li>
</ol>
<h2 id="结束"><a href="#结束" class="headerlink" title="结束"></a>结束</h2><p>以上就是整个文件分片上传的流程，当中的具体细节可以查看本人完成的对应的<a target="_blank" rel="noopener" href="https://food-billboard.github.io/chunk-file-load/#/">上传工具类库</a>，还有基于该类库封装的<code>React</code><a target="_blank" rel="noopener" href="https://food-billboard.github.io/chunk-file-load-component/#/">上传组件</a>  </p>

            </div>
            <hr>
            <div>
              <div class="post-metas mb-3">
                
                  <div class="post-meta mr-3">
                    <i class="iconfont icon-category"></i>
                    
                      <a class="hover-with-bg" href="/categories/%E6%96%87%E4%BB%B6/">文件</a>
                    
                      <a class="hover-with-bg" href="/categories/%E6%96%87%E4%BB%B6/%E4%B8%8A%E4%BC%A0/">上传</a>
                    
                      <a class="hover-with-bg" href="/categories/%E6%96%87%E4%BB%B6/%E4%B8%8A%E4%BC%A0/%E5%89%8D%E7%AB%AF/">前端</a>
                    
                  </div>
                
                
                  <div class="post-meta">
                    <i class="iconfont icon-tags"></i>
                    
                      <a class="hover-with-bg" href="/tags/upload-file-chunk/">upload file chunk</a>
                    
                  </div>
                
              </div>
              
                <p class="note note-warning">
                  
                    本博客所有文章除特别声明外，均采用 <a target="_blank" href="https://creativecommons.org/licenses/by-sa/4.0/deed.zh" rel="nofollow noopener noopener">CC BY-SA 4.0 协议</a> ，转载请注明出处！
                  
                </p>
              
              
                <div class="post-prevnext">
                  <article class="post-prev col-6">
                    
                    
                      <a href="/2022/02/09/%E5%B9%B3%E6%97%B6%E7%94%A8%E5%88%B0%E7%9A%84%E4%B8%80%E4%BA%9B%E4%BB%A3%E7%A0%81%E7%89%87%E6%AE%B5/">
                        <i class="iconfont icon-arrowleft"></i>
                        <span class="hidden-mobile">平时用到的一些代码片段</span>
                        <span class="visible-mobile">上一篇</span>
                      </a>
                    
                  </article>
                  <article class="post-next col-6">
                    
                    
                      <a href="/2021/11/19/gitmoji/">
                        <span class="hidden-mobile">gitmoji 优雅提交代码</span>
                        <span class="visible-mobile">下一篇</span>
                        <i class="iconfont icon-arrowright"></i>
                      </a>
                    
                  </article>
                </div>
              
            </div>

            
          </article>
        </div>
      </div>
    </div>
    
      <div class="d-none d-lg-block col-lg-2 toc-container" id="toc-ctn">
        <div id="toc">
  <p class="toc-header"><i class="iconfont icon-list"></i>&nbsp;目录</p>
  <div class="toc-body" id="toc-body"></div>
</div>

      </div>
    
  </div>
</div>

<!-- Custom -->


    

    
      <a id="scroll-top-button" aria-label="TOP" href="#" role="button">
        <i class="iconfont icon-arrowup" aria-hidden="true"></i>
      </a>
    

    
      <div class="modal fade" id="modalSearch" tabindex="-1" role="dialog" aria-labelledby="ModalLabel"
     aria-hidden="true">
  <div class="modal-dialog modal-dialog-scrollable modal-lg" role="document">
    <div class="modal-content">
      <div class="modal-header text-center">
        <h4 class="modal-title w-100 font-weight-bold">搜索</h4>
        <button type="button" id="local-search-close" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>
      <div class="modal-body mx-3">
        <div class="md-form mb-5">
          <input type="text" id="local-search-input" class="form-control validate">
          <label data-error="x" data-success="v"
                 for="local-search-input">关键词</label>
        </div>
        <div class="list-group" id="local-search-result"></div>
      </div>
    </div>
  </div>
</div>
    

    
  </main>

  <footer class="text-center mt-5 py-3">
  <div class="footer-content">
     <a href="https://hexo.io" target="_blank" rel="nofollow noopener"><span>Hexo</span></a> <i class="iconfont icon-love"></i> <a href="https://github.com/fluid-dev/hexo-theme-fluid" target="_blank" rel="nofollow noopener"><span>Fluid</span></a> <div style="font-size: 0.85rem"> <span id="timeDate">载入天数...</span> <span id="times">载入时分秒...</span> <script src="/js/duration.js"></script> <script src="/js/code-viewer.js"></script> </div> 
  </div>
  
  <div class="statistics">
    
    

    
      
        <!-- 不蒜子统计PV -->
        <span id="busuanzi_container_site_pv" style="display: none">
            总访问量 
            <span id="busuanzi_value_site_pv"></span>
             次
          </span>
      
      
        <!-- 不蒜子统计UV -->
        <span id="busuanzi_container_site_uv" style="display: none">
            总访客数 
            <span id="busuanzi_value_site_uv"></span>
             人
          </span>
      
    
  </div>


  

  
</footer>


  <!-- SCRIPTS -->
  
  <script  src="https://cdn.jsdelivr.net/npm/nprogress@0/nprogress.min.js" ></script>
  <link  rel="stylesheet" href="https://cdn.jsdelivr.net/npm/nprogress@0/nprogress.min.css" />

  <script>
    NProgress.configure({"showSpinner":false,"trickleSpeed":100})
    NProgress.start()
    window.addEventListener('load', function() {
      NProgress.done();
    })
  </script>


<script  src="https://cdn.jsdelivr.net/npm/jquery@3/dist/jquery.min.js" ></script>
<script  src="https://cdn.jsdelivr.net/npm/bootstrap@4/dist/js/bootstrap.min.js" ></script>
<script  src="/js/events.js" ></script>
<script  src="/js/plugins.js" ></script>

<!-- Plugins -->


  <script  src="/js/local-search.js" ></script>



  
    <script  src="/js/img-lazyload.js" ></script>
  



  



  
    <script  src="https://cdn.jsdelivr.net/npm/tocbot@4/dist/tocbot.min.js" ></script>
  
  
    <script  src="https://cdn.jsdelivr.net/npm/@fancyapps/fancybox@3/dist/jquery.fancybox.min.js" ></script>
  
  
    <script  src="https://cdn.jsdelivr.net/npm/anchor-js@4/anchor.min.js" ></script>
  
  
    <script defer src="https://cdn.jsdelivr.net/npm/clipboard@2/dist/clipboard.min.js" ></script>
  



  <script defer src="https://busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js" ></script>




  <script  src="https://cdn.jsdelivr.net/npm/typed.js@2/lib/typed.min.js" ></script>
  <script>
    (function (window, document) {
      var typing = Fluid.plugins.typing;
      var title = document.getElementById('subtitle').title;
      
      typing(title)
      
    })(window, document);
  </script>















<!-- 主题的启动项 保持在最底部 -->
<script  src="/js/boot.js" ></script>


<!-- hexo injector body_end start -->
  <script src="//cdn.jsdelivr.net/gh/bynotes/texiao/source/js/xiantiao.js"></script>
  <script src="//cdn.jsdelivr.net/gh/bynotes/texiao/source/js/xiaoxingxing.js"></script>
  <script src="//cdn.jsdelivr.net/gh/bynotes/texiao/source/js/dianjichuzi.js"></script>
<!-- hexo injector body_end end --><script src="/live2dw/lib/L2Dwidget.min.js?094cbace49a39548bed64abff5988b05"></script><script>L2Dwidget.init({"pluginRootPath":"live2dw/","pluginJsPath":"lib/","pluginModelPath":"assets/","tagMode":false,"debug":false,"model":{"jsonPath":"/live2dw/assets/shizuku.model.json"},"display":{"position":"right","width":150,"height":300,"mobile":{"show":true}},"log":false});</script></body>
</html>
